import { View, Text, Image, Button } from "@tarojs/components";

import listArrow from '@/assets/images/list-arrow.png'
import useProfileInfoAction from "@/hooks/useProfileInfoAction";
import { generateRegionData, handleCommonUpload, handleCompressImg, handleInitStoreBaseInfo, handleLoginCallback, showToast, toPage } from "@/common/util";
import { PAGE_TYPE, RESPONSE_CODE, STORE_KEY } from "@/common/config";
import { ActionSheet, ActionSheetItem } from "@antmjs/vantui";
import React, { Suspense, useEffect, useState } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import { API_URL } from "@/common/serviveApi";
import { DataItem, IRegionResponse, IResponseSuccess, IUserProfileEditPromise, IUserProfileInfo, USER_PROFILE_STATUS } from "@/typing";
import { observer } from 'mobx-react-lite';
// import { useStore } from '@/store';

import useInitAction from '@/hooks/useInitAction'
import useSeviceTypeAction from "@/hooks/useSeviceTypeAction";
import useJobTypeAction from "@/hooks/useJobTypeAction";
import './personInfo.scss'
import { handleRegionList } from "@/common/service";
import PendingPop from "@/components/pendingPop/pendingPop";
// import useRegionAction from "@/hooks/useRegionAction";
const AddSerivceDialog = React.lazy(() => import('@/components/addSerivceDialog/addSerivceDialog'));
const CascaderActionSheet = React.lazy(() => import('@/components/cascaderActionSheet/cascaderActionSheet'));
const JobDialog = React.lazy(() => import('@/components/jobDialog/jobDialog'));



const PersonInfo: React.FC = () => {
    // const {  jobStore } = useStore()

    // const { handleInitRegionList } = useRegionAction()

    const {
        handleInitJobDescT,
        setChannelCategoriesList,
        handleInitJobListT, channelCategoriesList
        // handleSubmitJobType,
    } = useJobTypeAction();
    const { handleShopUserprofileEdit, handleInitStoreProfileInfo, handleInitProfileInfo, } = useProfileInfoAction()
    const { handleInitServiceTypeDescT, handleInitServiceTypeList, serviceTypeList } = useSeviceTypeAction()
    const [pendingPopShow, setPendingPopShow] = useState(false)
    const [disableText, setDisableText] = useState('')
    const { bottomSafeHeight } = useInitAction()

    const [jobSelectShow, setJobSelectShow] = useState(false)
    const [avatarStatus, setAvatarStatus] = useState(USER_PROFILE_STATUS.disable)


    const [regionData, setRegionData] = useState<DataItem[]>()
    const [codeToText, setCodeToText] = useState<{ [key: string]: string }>({})
    const [areaVisible, setAreaVisible] = useState(false)
    const [area, setArea] = useState('')
    const [introduction, setIntroduction] = useState('')

    const [jobDesc, setJobDesc] = useState('');

    const [sex, setSex] = useState('')
    const [nickname, setNickname] = useState('');
    const [avatar, setUserAvatar] = useState('')

    const [sexSelectShow, setSexSelectShow] = useState(false)
    const [userService, setUserService] = useState('')

    const [serivceDialogShow, setSerivceDialogShow] = useState(false)


    const [actions] = useState<ActionSheetItem[]>([
        {
            name: '男',
        },
        {
            name: '女 ',
        },
    ])

    const handlePopStatusAction = (popStatus) => {
        setJobSelectShow(popStatus)
        handleInitJobDesc()
    }
    const handleEditCommonAction = async (editData, modifyFieldType: string, callback?: () => void) => {
        const editRes = await handleShopUserprofileEdit(editData) as IUserProfileEditPromise
        Taro.hideLoading({

        })
        const { code, msg, data } = editRes

        if (code === RESPONSE_CODE.SUCCESS) {
            if (modifyFieldType) {

                if (data) {
                    if (data.status === USER_PROFILE_STATUS.enable) {
                        if (callback) {
                            callback()


                        }
                    } else {
                        const storeBaseUserInfo = handleInitStore()
                        storeBaseUserInfo['modify_field'][modifyFieldType] = USER_PROFILE_STATUS.disable
                        Taro.setStorageSync(STORE_KEY.BASE_USER_INFO, JSON.stringify(storeBaseUserInfo))
                    }

                }

            }

            showToast(msg)




        } else if (code === RESPONSE_CODE.LOGIN_EXPIRE || code === RESPONSE_CODE.LOGIN_NEED) {
            handleLoginCallback(() => handleEditCommonAction(editData, modifyFieldType))

        } else {
            showToast(msg)
        }
    }
    const handleSelectSex = async (e) => {
        // console.log(e)

        const gender = e.detail.name === '男' ? 1 : 2
        handleEditCommonAction({ gender: gender }, 'gender', () => setSex(e.detail.name))

    }
    const handleSetArea = async (areaDetail, areaCodeObj) => {


        const provinceCode = areaCodeObj['province_code']
        const cityCode = areaCodeObj['city_code']
        const districtCode = areaCodeObj['district_code']

        handleEditCommonAction({ 'region_code[province_code]': provinceCode, 'region_code[city_code]': cityCode, 'region_code[district_code]': districtCode }, 'region_code', () => setArea(areaDetail))

    }
    const handleInitJobDesc = async () => {
        // console.log()
        if (channelCategoriesList.length === 0) {
            await handleInitStoreProfileInfo()
        }
        setChannelCategoriesList(channelCategoriesList)

        const storeJobIdList = JSON.parse(Taro.getStorageSync(STORE_KEY.JOB_ID_LIST) || '[]')
        if (storeJobIdList.length === 0) {

            const storeBaseUserInfo = handleInitStore()
            const jobIdList = storeBaseUserInfo['job_type_id'];
            const storeJobDesc = handleInitJobDescT(jobIdList);
            setJobDesc(storeJobDesc)
        } else {
            const storeJobIdDesc = JSON.parse(Taro.getStorageSync(STORE_KEY.JOB_ID_DESC) || '[]')
            const storeJobDescT = storeJobIdDesc.join('、')
            setJobDesc(storeJobDescT)
        }
    }
    const handleInitStore = async () => {
        handleInitJobListT()
        handleInitServiceTypeList()
        const regionRes = await handleRegionList() as IResponseSuccess<IRegionResponse>
        if (regionRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS && regionRes.data.code === RESPONSE_CODE.SUCCESS) {
            const regionDataList = regionRes.data.data;
            if (regionDataList && regionDataList.length > 0) {
                const { regionDataT, codeToTextT } = generateRegionData(regionDataList)
                setCodeToText(codeToTextT)
                setRegionData(regionDataT)
                const storeBaseUserInfo = handleInitStoreBaseInfo()

                if (storeBaseUserInfo) {
                    const baseUserInfo = storeBaseUserInfo


                    if (baseUserInfo.avatar) {
                        const userAvatar = `${baseUserInfo.avatar}`
                        Taro.setStorageSync(STORE_KEY.EDIT_AVATAR, userAvatar)
                        setUserAvatar(userAvatar)
                    }
                    if (baseUserInfo.nickname) {
                        setNickname(baseUserInfo.nickname)
                    }
                    if (baseUserInfo.gender) {
                        const sex = baseUserInfo.gender == 1 ? '男' : '女'
                        setSex(sex)
                    } else {
                        setSex('')
                    }
                    if (baseUserInfo.modify_field) {
                        const avatarModify = baseUserInfo.modify_field['avatar']
                        setAvatarStatus(avatarModify)
                    }
                    if (baseUserInfo.city_code) {

                        const area = `${codeToTextT[baseUserInfo['city_code']]}` === '市辖区' ? `${codeToTextT[baseUserInfo['province_code']]} / ${codeToTextT[baseUserInfo['district_code']]}` : `${codeToTextT[baseUserInfo['province_code']]} / ${codeToTextT[baseUserInfo['city_code']]} / ${codeToTextT[baseUserInfo['district_code']]}`
                        setArea(area)
                    }
                    if (baseUserInfo.introduction) {
                        setIntroduction(baseUserInfo.introduction)
                    }
                }
            }
        }



        // handleInitJobListT()
        // handleInitServiceTypeList()


    }
    const handleConfirmAction = async (jobIdList) => {

        if (jobIdList.length === 0) {
            showToast('请至少选择一个职业')

            return
        }
        const computedJobObj = {}
        jobIdList.forEach((id, index) => {

            const keyIdVal = `job_type_id[${[index]}]`
            computedJobObj[keyIdVal] = id


        })
        console.log(computedJobObj)

        // handleEditCommonAction({ ...computedJobObj }, '')
        // setJobSelectShow(false)
        Taro.showLoading({
            title: '修改中...',
            mask: true
        })
        const editRes = await handleShopUserprofileEdit({ ...computedJobObj }) as IUserProfileEditPromise
        Taro.hideLoading({

        })
        const { code, msg } = editRes
        if (code === RESPONSE_CODE.SUCCESS) {
            showToast('保存成功')
            const storeJobDesc = handleInitJobDescT(jobIdList);
            setJobDesc(storeJobDesc)
            setJobSelectShow(false)

        } else if (code === RESPONSE_CODE.LOGIN_EXPIRE || code === RESPONSE_CODE.LOGIN_NEED) {
            handleLoginCallback(() => handleConfirmAction(jobIdList))

        } else {
            showToast(msg)
        }

    }

    const handleEditCommonJudge = async (modifyfieldKey, modifyfieldValue, callback: () => void) => {
        handleInitProfileInfo().then((profileInfoData: IUserProfileInfo) => {
            const { code, data } = profileInfoData
            if (code === RESPONSE_CODE.SUCCESS) {
                const { modify_field, status } = data

                const storeBaseUserInfo = handleInitStoreBaseInfo();
                if (status === USER_PROFILE_STATUS.enable) {
                    storeBaseUserInfo['modify_field'] = modify_field;
                    const modifyField = storeBaseUserInfo.modify_field
                    if (modifyField[`${modifyfieldKey}`] === USER_PROFILE_STATUS.disable) {
                        setDisableText(modifyfieldValue)
                        setPendingPopShow(true)
                    } else if (modifyField[`${modifyfieldKey}`] === USER_PROFILE_STATUS.enable) {
                        callback()
                    }
                }
            }


        })






    }
    const handleInitServiceType = () => {
        const serviceType = JSON.parse(Taro.getStorageSync(STORE_KEY.ADD_SERVICE_TYPE_DESC) || '[]')
        if (serviceType.length > 0) {
            const serviceTypeT = serviceType.join('、')
            setUserService(serviceTypeT)
        }
    }
    const handleOnChooseAvatar = async (e) => {
        const { avatarUrl } = e.detail
        handleCompressImg([{ url: avatarUrl }], 80).then(async (compressedPath) => {
            const thumb = String(compressedPath)

            let uploadAvatarUrlRes = await handleCommonUpload(thumb);

            if (uploadAvatarUrlRes.code === RESPONSE_CODE.LOGIN_EXPIRE || uploadAvatarUrlRes.code === RESPONSE_CODE.LOGIN_NEED) {
                handleLoginCallback(async () => {
                    uploadAvatarUrlRes = await handleCommonUpload(thumb);
                })

            } else if (uploadAvatarUrlRes.code === RESPONSE_CODE.SUCCESS) {
                const fileUrl = uploadAvatarUrlRes.fileUrl
                // console.log(fileUrl)
                const editRes = await handleShopUserprofileEdit({ avatar: fileUrl }) as IUserProfileEditPromise
                Taro.hideLoading({

                })
                setDisableText('头像')
                setPendingPopShow(true)
                setAvatarStatus(USER_PROFILE_STATUS.disable)
                const storeBaseUserInfo = handleInitStoreBaseInfo()
                storeBaseUserInfo['modify_field']['avatar'] = USER_PROFILE_STATUS.disable
                Taro.setStorageSync(STORE_KEY.BASE_USER_INFO, JSON.stringify(storeBaseUserInfo))
                const { msg } = editRes
                showToast(msg)

            }
        })


    }
    const handleConfirmServiceAction = async (serviceIdList) => {
        const idList = JSON.parse(Taro.getStorageSync(STORE_KEY.ADD_SERVICE_TYPE) || '[]')
        if (serviceIdList.length > 0) {
            const idListSum = serviceIdList.reduce((pre, cur) => {
                return pre + cur
            })
            const idListSumT = idList.reduce((pre, cur) => {
                return pre + cur
            })
            if (idList.length === serviceIdList.length && idListSum === idListSumT) {
                setSerivceDialogShow(false)

            } else {
                const computedServiceObj = {}
                serviceIdList.forEach((typeId, index) => {

                    const keyIdVal = `service_type_id[${[index]}]`
                    computedServiceObj[keyIdVal] = typeId


                })
                // const computedServiceObj = handleInitSubmitServiceTypeInfo(serviceIdList)
                Taro.showLoading({
                    title: '修改中...',
                    mask: true
                })
                const editRes = await handleShopUserprofileEdit({ ...computedServiceObj }) as IUserProfileEditPromise
                Taro.hideLoading({

                })
                const { code, msg } = editRes
                if (code === RESPONSE_CODE.SUCCESS) {
                    showToast('保存成功')
                    const storeTypeDesc = handleInitServiceTypeDescT(serviceIdList)
                    setSerivceDialogShow(false)
                    setUserService(storeTypeDesc)
                } else if (code === RESPONSE_CODE.LOGIN_EXPIRE || code === RESPONSE_CODE.LOGIN_NEED) {
                    handleLoginCallback(() => handleConfirmServiceAction(serviceIdList))

                } else {
                    showToast(msg)
                }
            }

        } else {
            Taro.showToast({
                title: '请选择服务类型',
                icon: 'none'
            })
        }
    }
    const handleGoEditVideoPage = () => {
        handleEditCommonJudge('media_video', '视频', () => {

            handleInitProfileInfo().then((profileInfoData: IUserProfileInfo) => {
                const { code, data } = profileInfoData
                if (code === RESPONSE_CODE.SUCCESS) {
                    const { media_video } = data
                    if (media_video) {
                        Taro.setStorageSync(STORE_KEY.VIDEO_URL, media_video)
                    }
                    toPage(PAGE_TYPE.EDIT_VIDEO)
                }

            })

        })
    }
    const handleGoEditPhotoPage = () => {
        handleEditCommonJudge('media_img', '图片', () => {

            handleInitProfileInfo().then((profileInfoData: IUserProfileInfo) => {
                const { code, data } = profileInfoData
                if (code === RESPONSE_CODE.SUCCESS) {
                    const { media_img } = data
                    if (media_img && media_img.length > 0) {
                        Taro.setStorageSync(STORE_KEY.PHOTO_LIST, JSON.stringify(media_img))
                    }
                    toPage(PAGE_TYPE.EDIT_PHOTO)
                }

            })

        })
    }
    const handleGoEditTopicPage = () => {
        handleEditCommonJudge('topic', '话题', () => {

            handleInitProfileInfo().then((profileInfoData: IUserProfileInfo) => {
                const { code, data } = profileInfoData
                if (code === RESPONSE_CODE.SUCCESS) {
                    const { topic } = data
                    if (topic && topic.length > 0) {
                        Taro.setStorageSync(STORE_KEY.TOPIC, JSON.stringify(topic))
                    }
                    toPage(PAGE_TYPE.TOPIC_SETTING)
                }

            })

        })
    }
    const handleAvatarTip = () => {
        setDisableText('头像')
        setPendingPopShow(true)
    }
    const handlePopServiceAction = (popStatus) => {
        setSerivceDialogShow(popStatus)

        // handleInitServiceTypeDesc()
    }
    const handleCallBack = () => {
        setPendingPopShow(false)
    }

    useDidShow(() => {
        handleInitStore()
        handleInitJobDesc()
        handleInitServiceType();

    })
    // useEffect(() => {
    //     handleInitStore()

    // }, []);
    useEffect(() => {
        // handleInitJobDesc()

        if (jobSelectShow) {
            handleInitJobDesc()
        }

    }, [jobSelectShow])


    return <>
        <View className="w-full min-h-100vh bg-#F6F6F6 box-border py-28px" style={{ paddingBottom: bottomSafeHeight > 0 ? bottomSafeHeight + 'px' : '90rpx' }}>
            <View>
                <View className="pl-42px pr-48px box-border flex items-center justify-between w-full h-124px bg-#fff relative">
                    <Text className="text-#161618 text-32px">头像</Text>
                    {avatarStatus === USER_PROFILE_STATUS.disable ? <Button className='user-button text-#161618 mx-0 text-transparent font-medium border-0 rounded-0 bg-transparent absolute right-0 top-20px px-60px' onClick={handleAvatarTip} >哈哈哈哈哈哈哈哈哈哈</Button> :

                        <Button className='user-button text-#161618 mx-0 text-transparent font-medium border-0 rounded-0 bg-transparent absolute right-0 top-20px px-60px' openType='chooseAvatar' onChooseAvatar={handleOnChooseAvatar}>哈哈哈哈哈哈哈哈哈哈</Button>}

                    <View className="flex items-center">
                        <View className='w-72px h-72px rounded-72px overflow-hidden'>
                            <Image src={`${API_URL}${avatar}`} className="w-72px h-72px"></Image>
                        </View>

                        <Image src={listArrow} className="w-19px h-30px ml-26px"></Image>

                    </View>
                </View>
                <View className="pl-42px pr-48px box-border">
                    <View className="w-full h-1px bg-#E9E9E9"></View>
                </View>

                <View className="pl-42px pr-48px box-border flex items-center justify-between w-full h-124px bg-#fff" onClick={() => handleEditCommonJudge('nickname', '昵称', () => { toPage(PAGE_TYPE.EDIT_NICKNAME) })}>
                    <Text className="text-#161618 text-32px">昵称</Text>
                    <View className="flex items-center">
                        <Text className="text-#666666 text-32px">{nickname}</Text>
                        <Image src={listArrow} className="w-19px h-30px ml-26px"></Image>

                    </View>
                </View>
                <View className="pl-42px pr-48px box-border">
                    <View className="w-full h-1px bg-#E9E9E9"></View>
                </View>

                <View className="pl-42px pr-48px box-border flex items-center justify-between w-full h-124px bg-#fff" onClick={() => handleEditCommonJudge('gender', '性别', () => { setSexSelectShow(true) })}>
                    <Text className="text-#161618 text-32px">性别</Text>
                    <View className="flex items-center">
                        <Text className="text-#666666 text-32px">{sex}</Text>
                        <Image src={listArrow} className="w-19px h-30px ml-26px"></Image>

                    </View>
                </View>
                <View className="pl-42px pr-48px box-border">
                    <View className="w-full h-1px bg-#E9E9E9"></View>
                </View>

                <View className="pl-42px pr-48px box-border flex items-center justify-between w-full h-124px bg-#fff" onClick={() => handleEditCommonJudge('region_code', '地区', () => { setAreaVisible(true) })}>
                    <Text className="text-#161618 text-32px">地区</Text>
                    <View className="flex items-center">
                        <Text className="text-#666666 text-32px">{area}</Text>
                        <Image src={listArrow} className="w-19px h-30px ml-26px"></Image>

                    </View>
                </View>
                <View className="pl-42px pr-48px box-border">
                    <View className="w-full h-1px bg-#E9E9E9"></View>
                </View>
                <View className="pl-42px pr-48px box-border flex items-center justify-between w-full h-124px bg-#fff" onClick={() => handleEditCommonJudge('job_type_id', '职业', () => setJobSelectShow(true))}>
                    <View className="text-#161618 text-32px w-66px">职业</View>
                    <View className="flex items-center justify-end flex-1 ml-20px">
                        <Text className="text-#666666 text-32px">{jobDesc}</Text>
                        <Image src={listArrow} className="w-19px h-30px ml-26px"></Image>

                    </View>
                </View>
                <View className="pl-42px pr-48px box-border">
                    <View className="w-full h-1px bg-#E9E9E9"></View>
                </View>
                <View className="pl-42px pr-48px box-border flex items-center justify-between w-full h-124px bg-#fff" onClick={() => handleEditCommonJudge('introduction', '简介', () => { toPage(PAGE_TYPE.EDIT_DESCRIPTION) })}>
                    <View className="text-#161618 text-32px w-66px">简介</View>
                    <View className="flex items-center justify-end flex-1 ml-20px">
                        <Text className="text-#666666 text-32px">{introduction}</Text>
                        <Image src={listArrow} className="w-19px h-30px ml-26px"></Image>

                    </View>
                </View>


            </View>


            <View className="mt-24px">


                <View className="pl-42px pr-48px box-border flex items-center justify-between w-full h-124px bg-#fff" onClick={() => handleEditCommonJudge('readme', '自述', () => { toPage(PAGE_TYPE.USER_README) })}>
                    <Text className="text-#161618 text-32px">自述</Text>
                    <View className="flex items-center">

                        <Image src={listArrow} className="w-19px h-30px ml-26px"></Image>

                    </View>
                </View>
                <View className="pl-42px pr-48px box-border">
                    <View className="w-full h-1px bg-#E9E9E9"></View>
                </View>

                <View className="pl-42px pr-48px box-border flex items-center justify-between w-full h-124px bg-#fff" onClick={handleGoEditVideoPage}>
                    <Text className="text-#161618 text-32px">视频</Text>
                    <View className="flex items-center">

                        <Image src={listArrow} className="w-19px h-30px ml-26px"></Image>

                    </View>
                </View>
                <View className="pl-42px pr-48px box-border">
                    <View className="w-full h-1px bg-#E9E9E9"></View>
                </View>

                <View className="pl-42px pr-48px box-border flex items-center justify-between w-full h-124px bg-#fff" onClick={handleGoEditPhotoPage}>
                    <Text className="text-#161618 text-32px">照片</Text>
                    <View className="flex items-center">

                        <Image src={listArrow} className="w-19px h-30px ml-26px"></Image>

                    </View>
                </View>


            </View>

            <View className="mt-24px">

                <View className="pl-42px pr-48px box-border flex items-center justify-between w-full h-124px bg-#fff" onClick={handleGoEditTopicPage} >
                    <Text className="text-#161618 text-32px">可聊话题</Text>
                    <View className="flex items-center">

                        <Image src={listArrow} className="w-19px h-30px ml-26px"></Image>

                    </View>
                </View>
                <View className="pl-42px pr-48px box-border">
                    <View className="w-full h-1px bg-#E9E9E9"></View>
                </View>
                <View className="pl-42px pr-48px box-border flex items-center justify-between w-full h-124px bg-#fff" onClick={() => setSerivceDialogShow(true)}>
                    <Text className="text-#161618 text-32px">提供服务</Text>
                    <View className="flex items-center">
                        <Text className="text-#161618 text-32px">{userService}</Text>

                        <Image src={listArrow} className="w-19px h-30px ml-26px"></Image>

                    </View>
                </View>



            </View>
        </View>
        <ActionSheet
            cancelText='取消'
            show={sexSelectShow}
            actions={actions}
            onClose={() => setSexSelectShow(false)}
            onCancel={() => setSexSelectShow(false)}
            onSelect={(e) => handleSelectSex(e)}
        />
        <Suspense>
            <JobDialog channelCategoriesList={channelCategoriesList} show={jobSelectShow} handlePopStatus={handlePopStatusAction} handleConfirm={handleConfirmAction}></JobDialog>
        </Suspense>
        <Suspense>
            {regionData && <CascaderActionSheet codeToText={codeToText} regionData={regionData} areaVisible={areaVisible} handleCloseAreaAction={() => setAreaVisible(false)} handleAreaChangeAction={(areaDetail, areaCodeObj) => handleSetArea(areaDetail, areaCodeObj)}></CascaderActionSheet>}

        </Suspense>
        <Suspense>
            <AddSerivceDialog serviceTypeList={serviceTypeList} show={serivceDialogShow} handlePopStatus={handlePopServiceAction} handleConfirm={handleConfirmServiceAction}></AddSerivceDialog>
        </Suspense>


        <Suspense>
            <PendingPop show={pendingPopShow} disableText={disableText} callBack={handleCallBack}></PendingPop>
        </Suspense>

        {/* 
        <Popup show={pendingPopShow} closeOnClickOverlay={false} position="bottom" safeAreaInsetBottom={false} >
            <View className="pt-38px box-border flex flex-col items-center">
                <View className="text-#888888 text-28px font-medium">新{disableText}将在审核通过后对外展示</View>
                <View className="w-full h-1px bg-#E8E8E8 mt-32px"></View>
                <View className="w-full text-center pt-46px text-#333333 font-medium" style={{ paddingBottom: bottomSafeHeight > 0 ? bottomSafeHeight + 'px' : '90rpx' }} onClick={handleClosePendingPop}>确定</View>
            </View>
        </Popup> */}


    </>
}
export default observer(PersonInfo);